package com.android.topview.watermelon.exchange

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.android.topview.watermelon.R

internal class ExchangeListAdapter(
    default: ExchangeCode
) : RecyclerView.Adapter<ExchangeListAdapter.ViewHolder>() {

    internal var selectIndex = EXCHANGE_CODE_ARRAY.indexOf(default)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            LayoutInflater.from(parent.context)
                .inflate(R.layout.item_exchange_list, parent, false)
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        with(holder.tv) {
            text = EXCHANGE_CODE_ARRAY[position].msg
            setBackgroundResource(
                if (holder.adapterPosition == selectIndex) {
                    R.color.gray_40
                } else {
                    R.color.transparent
                }
            )
            setOnClickListener {
                val last = selectIndex
                selectIndex = holder.adapterPosition
                notifyItemChanged(last)
                setBackgroundResource(R.color.gray_40)
            }
        }
    }

    override fun getItemCount() = EXCHANGE_CODE_ARRAY.size

    internal class ViewHolder(v: View) : RecyclerView.ViewHolder(v) {
        internal val tv: TextView = v.findViewById(R.id.tv_exchange_list_item)
    }

}